package com.alog.senior.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Auther: Ye Zhengdong
 * @Date: 2019/1/30 14:15
 * @Description:
 */
public class DruidUtil {
    private static DataSource ds ;
    static{
        try {
            Properties properties = new Properties();
            properties.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取连接池
     */
    public static DataSource getDataSource(){
        return ds;
    }
    /**
     * 获取连接
     */
    public static Connection getConn() throws SQLException {
        return ds.getConnection();
    }

    /**
     *  释放资源
     */
    public static void close(ResultSet rs, Statement smt, Connection conn){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(smt != null){
            try {
                smt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     *  释放资源
     */
    public static void close(Statement smt, Connection conn){
        close(null, smt, conn);
    }
}
